package com.dean.ui.panel.impl;

import cn.hutool.core.util.StrUtil;
import com.dean.entity.SysDbConnInfo;
import com.dean.service.DbConnService;
import com.dean.ui.panel.DeanPanel;
import com.dean.ui.utils.UiUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * 数据库链接管理
 */
public class DbConnManagerPanel extends BasePanel{

	private static final Logger logger = LoggerFactory.getLogger(DbConnManagerPanel.class);

    /**
     * 数据库展示表头
     */
    private final String [] heads = {"CONNECT_NAME","DB_DRIVER","DB_URL","DB_USERNAME","DB_PASS_WORD"};
    // 下
    private  JLabel dbDriverLabel;
    private  JTextField dbDriver;

    private  JLabel dbUrlLabel;
    private  JTextField dbUrl;

    private  JLabel dbUsernameLabel;
    private  JTextField dbUsername;

    private  JLabel dbPasswordLable;
    private  JTextField dbPassword;

    private  JLabel dbCfgNameLabel;
    private  JTextField dbCfgName;


    // 中
    private  JButton saveCfgBtn;
    private JButton queryBtn;
    private JButton delCfgBtn;

    // 下
    private JTable table;

    /**
     * ui 布局  top
     */
	public void mainUi(){
        // 第一行
        dbDriverLabel = new JLabel("db_driver:");
        UiUtils.setLeftBounds(dbDriverLabel,1);
        panel.add(dbDriverLabel);

        dbDriver = new JTextField("oracle.jdbc.driver.OracleDriver");
        UiUtils.setLeftBounds(dbDriver,1);
        panel.add(dbDriver);

        dbUrlLabel = new JLabel("db_url:");
        UiUtils.setRightBounds(dbUrlLabel,1);
        panel.add(dbUrlLabel);

        dbUrl = new JTextField("jdbc:oracle:thin:@10.1.3.36:1521:oradb");
        UiUtils.setRightBounds(dbUrl,1);
        panel.add(dbUrl);

        // 第二行
        dbUsernameLabel = new JLabel("db_username:");
        UiUtils.setLeftBounds(dbUsernameLabel,2);
        panel.add(dbUsernameLabel);

        dbUsername = new JTextField("einfo");
        UiUtils.setLeftBounds(dbUsername,2);
        panel.add(dbUsername);

        dbPasswordLable = new JLabel("db_password:");
        UiUtils.setRightBounds(dbPasswordLable,2);
        panel.add(dbPasswordLable);

        dbPassword = new JTextField("einfo");
        UiUtils.setRightBounds(dbPassword,2);
        panel.add(dbPassword);

        // 第三行
        dbCfgNameLabel = new JLabel("数据库连接名称:");
        UiUtils.setLeftBounds(dbCfgNameLabel,3);
        panel.add(dbCfgNameLabel);

        dbCfgName = new JTextField("einfo");
        UiUtils.setLeftBounds(dbCfgName,3);
        panel.add(dbCfgName);

        queryBtn = new JButton("查询");
        UiUtils.setRightButtonBounds(queryBtn,3,3);
        panel.add(queryBtn);

        delCfgBtn = new JButton("删除");
        UiUtils.setRightButtonBounds(delCfgBtn,3,2);
        panel.add(delCfgBtn);

        saveCfgBtn = new JButton("保存配置信息");
        UiUtils.setRightButtonBounds(saveCfgBtn,3,1);
        panel.add(saveCfgBtn);

        // table init
        DefaultTableModel defaultTableModel = new DefaultTableModel(new Object[0][0],heads);
        table = new JTable(defaultTableModel);
        table.setShowGrid(true);
        JScrollPane tablelPane = new JScrollPane(table);
        UiUtils.setTableBounds(tablelPane,4);
        panel.add(tablelPane);

    }

    public void mainScript(){
        queryBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                initTables();
            }
        });
        saveCfgBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveCfg();
            }
        });
        delCfgBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                delCfg();
            }
        });
        // table 监听事件
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                // 鼠标释放不用处理
                if(e.getValueIsAdjusting() == true){
                    return;
                }
                int row = table.getSelectedRow();
                int rowCount = table.getRowCount();
                logger.debug("{},{}",row,rowCount);

                if(row > -1 && row < rowCount){
                    int colCount =  table.getColumnCount();
                    for (int i = 0; i < colCount; i++) {
                        logger.debug("{}{}",table.getColumnName(i),table.getValueAt(row,i));
                        setForm(table.getColumnName(i),table.getValueAt(row,i)==null?null:table.getValueAt(row,i).toString());
                    }
                }
            }
        });

        // 加载配置文件
        initTables();

    }

    @Override
    public void initProperties() {
        
    }

    private void  setForm(String key,String value){
	    // "CONNECT_NAME","DB_DRIVER","DB_URL","DB_USERNAME","DB_PASS_WORD"
	    if("DB_DRIVER".equals(key)){
            dbDriver.setText(value);
        }else if("DB_URL".equals(key)) {
            dbUrl.setText(value);
        }else if("DB_USERNAME".equals(key)) {
	        dbUsername.setText(value);
        }else if("DB_PASS_WORD".equals(key)) {
	        dbPassword.setText(value);
        }else  if("CONNECT_NAME".equals(key)){
            dbCfgName.setText(value);
        }
    }

    private void delCfg(){
        String connName = table.getValueAt(table.getSelectedRow(),0)==null?"":table.getValueAt(table.getSelectedRow(),0).toString();
        int confirm = JOptionPane.showConfirmDialog(panel,"是否删除链接名称为["+connName+"]的数据？");
        logger.debug("confirm:{}",confirm);
        if(confirm != 0){
            return;
        }
        if(DbConnService.getInstance().del(connName)) {
            // 重新加载表格
            initTables();
            JOptionPane.showMessageDialog(panel,"配置信息删除成功", "SUCESS",JOptionPane.INFORMATION_MESSAGE);
        }else {
            JOptionPane.showMessageDialog(panel,"配置信息删除失败", "ERROR",JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveCfg(){
        SysDbConnInfo connectInfo = new SysDbConnInfo();
        connectInfo.setConnName(dbCfgName.getText());
        connectInfo.setUsername(dbUsername.getText());
        connectInfo.setPassword(dbPassword.getText());
        connectInfo.setUrl(dbUrl.getText());
        connectInfo.setDriver(dbDriver.getText());

        // 校验
        if(StrUtil.isBlank(connectInfo.getConnName())){
            JOptionPane.showMessageDialog(panel, "校验未通过,数据库连接名称不能为空", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(StrUtil.isBlank(connectInfo.getDriver())){
            JOptionPane.showMessageDialog(panel, "校验未通过,数据库驱动不能为空", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(StrUtil.isBlank(connectInfo.getUrl())){
            JOptionPane.showMessageDialog(panel, "校验未通过,数据库URL不能为空", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(StrUtil.isBlank(connectInfo.getUsername())){
            JOptionPane.showMessageDialog(panel, "校验未通过,数据库用户名不能为空", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(StrUtil.isBlank(connectInfo.getPassword())){
            JOptionPane.showMessageDialog(panel, "校验未通过,数据库用户密码不能为空", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(DbConnService.getInstance().save(connectInfo)) {
            // 重新加载表格
            initTables();
            JOptionPane.showMessageDialog(panel,"配置信息保存成功", "SUCESS",JOptionPane.INFORMATION_MESSAGE);
        }else {
            JOptionPane.showMessageDialog(panel,"配置信息保存失败", "ERROR",JOptionPane.ERROR_MESSAGE);
        }

    }

    /**
     * 初始化表格数据
     */
    private void initTables(){
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.getDataVector().clear();
        // 初始化表格
        List<SysDbConnInfo> connInfos = DbConnService.getInstance().getConnInfos();
        connInfos.forEach(connInfo -> {
            String[] row = {connInfo.getConnName(),connInfo.getDriver(),connInfo.getUrl(),connInfo.getUsername(),connInfo.getPassword()};
            tableModel.addRow(row);
        });
    }

}
